package com.dong.c07_netty_simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2020-03-19 19:55
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        /**
         * 说明:
         *  1. 创建了两个线程组, bossgroup, workgroup
         *  2. bossGroup 只处理连接请求
         *  3. workGroup 与客户端业务处理
         *  4. 两个都是死循环
         *  5.
         *
         *  bossGroup & workGropy 含有的子线程(NioEventLoop)数量  default availableProcessors*2
         *
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
        try {
            //创建服务器端的启动对象,配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            //链式编程进行设置
            //设置两个线程组
            bootstrap.group(bossGroup,workGroup)
                    // 设置channel类型
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列, 等待连接个数
                    .option(ChannelOption.SO_BACKLOG,128)
                    //设置保持活动连接状态  线程队列等待连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    //给我们的workerGroup的EventLoop对应的管道,设置处理器
                    //创建一个通道, 初始化
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //可以使用一个劲结合管理Socketchannel , 在推送消息时, 可以将业务加入到各个Channel对应的nioEventLoop的TaskQueue或ScheduleTaskQueue
                            System.out.println("客户端socketChannel hashcode: "+socketChannel.hashCode());
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("server is ready....");
            //绑定端口, 且同步
            ChannelFuture channelFuture = bootstrap.bind(6688).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
